﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraTreeList;

namespace Lamex.mMaterial.UI
{
    public partial class frmMC_BOM_Query : frmBaseChild
    {
        //全局变量-定义节点的最大展开次数
        int maxId = 0;
        public frmMC_BOM_Query()
        {
            InitializeComponent();
        }

        private void cmbSearchType_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmbSearchType.Text == "CSMB-树形BOM")
            {
                treeList1.ClearNodes();
                treeList1.DataSource = null;
                gridControl1.Visible = false;
                treeList1.Visible = true;
            }
            else
            {
                gridView1.Columns.Clear();
                gridControl1.DataSource = null;
                gridControl1.Visible = true;
                treeList1.Visible = false;
            }
        }

        private void sbtnRefresh_Click(object sender, EventArgs e)
        {
            #region 开发说明

            /*
             * 数据源为：PD_Bom
             * CS11-逐层BOM、CS12-多层BOM、CS13-汇总BOM按要求格式查询memoExEdit1、或memoExEdit2，或memoExEdit1-memoExEdit2之间物料BOM数据
             * CS14-BOM比较，按要求格式查询memoExEdit1、memoExEdit2物料BOM数据（CS13-汇总BOM），显示时在结果一栏显示图标
             * CS15-反查BOM分仅父层、所有层两种查询模式
             * CSMB-树形BOM用树图显示所查询到的BOM，数据同CS12-多层BOM
             */

            #endregion
            string[] str1 = memoExEdit1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] str2 = memoExEdit2.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (string.IsNullOrEmpty(cmbSearchType.Text))
            {
                XtraMessageBox.Show("请选择查询方式！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (str1.Length <= 0 && str2.Length <= 0)
            {
                DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show("没有输入物料编号,查询时间可能过长,是否继续？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.No)
                {
                    return;
                }
            }
            using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在查询数据......", new Size(400, 80)))
            {
                gridView1.Columns.Clear();
                gridControl1.DataSource = null;
                string strProName;
                string strColumsName;
                List<string> lst = new List<string>();
                switch (cmbSearchType.Text)
                {
                    case "CS11-逐层BOM":
                        strProName = "CS11";
                        strColumsName = "PMatNo";
                        break;
                    case "CS12-多层BOM":
                        strProName = "CS12";
                        strColumsName = "PMatNo";
                        break;
                    case "CS13-汇总BOM":
                        strProName = "CS13";
                        strColumsName = "PMatNo";
                        break;
                    case "CS14-BOM比较":
                        strProName = "CS14";
                        strColumsName = "PMatNo";
                        break;
                    case "CS15-反查BOM-仅父层":
                        strProName = "CS15_SINGLE";
                        strColumsName = "MatNo";
                        break;
                    case "CS15-反查BOM-所有层":
                        strProName = "CS15_ALL";
                        strColumsName = "MatNo";
                        break;
                    case "CSMB-树形BOM":
                        strProName = "CSMB";
                        strColumsName = "PMatNo";
                        break;
                    default:
                        strProName = "CS11";
                        strColumsName = "PMatNo";
                        break;
                }
                lst.Add(strProName);

                string strWhere_MatNo = "1=1 ";
                StringBuilder sbmemoEx1 = new StringBuilder();

                //物料BOM对比需输入起始物料和结束物料
                if (strProName == "CS14")
                {
                    if (str1.Length != 1 || str2.Length != 1)
                    {
                        XtraMessageBox.Show("起始物料和结束物料必须都是一个且不能输入多个物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (str1[0] == str2[0])
                    {
                        XtraMessageBox.Show("起始物料和结束物料不能相同！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    strWhere_MatNo = strWhere_MatNo + " AND PMatNo IN('" + str1[0] + "','" + str2[0] + "')";

                }

                else
                {
                    if (str1.Length > 0)
                    {
                        if (str2.Length > 0)
                        {
                            if (str1.Length > 1 || str2.Length > 1)
                            {
                                XtraMessageBox.Show("范围查询时起始物料和结束物料必须都是一个,不能输入多个物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            //区间范围查询
                            else
                            {
                                strWhere_MatNo = strWhere_MatNo + " AND " + strColumsName + " between '" + str1[0] + "' and '" + str2[0] + "'";
                            }
                        }
                        else
                        {
                            sbmemoEx1.AppendFormat(" AND " + strColumsName + " IN('{0}') ", string.Join("','", str1.ToArray()));
                            strWhere_MatNo = strWhere_MatNo + sbmemoEx1.ToString();
                        }
                    }
                }


                lst.Add(strWhere_MatNo);
                //数量
                string inputQty = "1";
                if (txtQty.Text.Length > 0)
                    inputQty = txtQty.Text.Trim();
                lst.Add(inputQty);
                DataTable dt = Lamex.Base.BaseBuildSql.GetProDataTable("p_Cal_PD_BOM", lst);
                if(cmbSearchType.Text== "CS11-逐层BOM")
                {
                    DataTable dtNew = dt.Clone();

                    DataTable dt1 = dt.DefaultView.ToTable(true, "PMatNo");
                    for (int k = 0; k < dt1.Rows.Count; k++)
                    {
                        DataTable dt2 = dt.Select("PMatNo='" + dt1.Rows[k]["PMatNo"].ToString() + "'").CopyToDataTable();
                        DataTable dt3 = dt2.DefaultView.ToTable(true, "PMatNo_Temp");
                        for (int i = 0; i < dt3.Rows.Count; i++)
                        {
                            DataRow[] dr = dt.Select("PMatNo='" + dt1.Rows[k]["PMatNo"].ToString() + "'" +
                                " and PMatNo_Temp='" + dt3.Rows[i]["PMatNo_Temp"].ToString() + "'"); //+
                               // " and MatNo_Temp='" + dt3.Rows[i]["MatNo_Temp"].ToString() + "'");
                            foreach (DataRow row in dr)
                            {
                                dtNew.ImportRow(row);
                            }
                        }
                    }

                 
                    gridControl1.DataSource = dtNew;
                }
                else
                gridControl1.DataSource = dt;

                if (cmbSearchType.Text == "CS14-BOM比较")
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox img = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();
                    gridView1.Columns["Relsut"].ColumnEdit = img;
                    img.SmallImages = imageCollection1;
                    img.Items.AddRange(new DevExpress.XtraEditors.Controls.ImageComboBoxItem[] {
            new DevExpress.XtraEditors.Controls.ImageComboBoxItem("相同", true, 0),
            new DevExpress.XtraEditors.Controls.ImageComboBoxItem("不同", false, 1)});
                }
                if (cmbSearchType.Text == "CSMB-树形BOM")
                {
                    maxId = Convert.ToInt32(dt.Compute("Max(LevelNo)", "true"));//最大节点

                    //拆分生成父子节点
                    //添加父节点和子节点列
                    DataColumn dc1 = new DataColumn("PId", typeof(string));
                    dc1.DefaultValue = "";
                    dt.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn("ChildId", typeof(string));
                    dc2.DefaultValue = "";
                    dt.Columns.Add(dc2);

                    //dt需排序后再进行逻辑拆分
                    //排序字段 PMatNo,OrderNo
                    DataView dv = dt.DefaultView;
                    dv.Sort = "PMatNo,OrderNo";
                    dt = dv.ToTable();
                    char s = Convert.ToChar("_");
                    //根节点
                    string strParentId = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow[] rows = dt.Select("OrderNo='" + dt.Rows[i]["OrderNo"].ToString() + "'");
                        foreach (DataRow row in rows)
                        {
                            //判断"_"出现的次数
                            string strOrderNo = row["OrderNo"].ToString();

                            var qry = from c in strOrderNo
                                      where c == s
                                      select c;

                            if (strOrderNo.Contains("_0"))
                            {
                                row["PId"] = strOrderNo;
                                row["ChildId"] = strOrderNo;
                                strParentId = strOrderNo;
                            }
                            else if (!strOrderNo.Contains("_0") && qry.Count() == 1)
                            {
                                row["PId"] = strParentId;
                                row["ChildId"] = strOrderNo;
                            }
                            else
                            {
                                row["PId"] = strOrderNo.Substring(0, strOrderNo.LastIndexOf("_"));
                                row["ChildId"] = strOrderNo;
                            }

                        }
                    }

                    //自定义加载  添加到Panel上
                    //TreeList treeList1 = new TreeList();
                    //treeList1.Parent = this;
                    //treeList1.Dock = DockStyle.Fill;
                    //treeList1.BeginUnboundLoad();
                    //treeList1.ClearNodes();                 
                    treeList1.KeyFieldName = "ChildId";
                    treeList1.ParentFieldName = "PId";
                    treeList1.OptionsBehavior.PopulateServiceColumns = true;
                    treeList1.DataSource = dt;
                    //不显示新增父子节点列
                    treeList1.Columns[treeList1.KeyFieldName].Visible = false;
                    treeList1.Columns[treeList1.ParentFieldName].Visible = false;
                    treeList1.Columns["OrderNo"].Visible = false;
                    //展开
                    // treeList1.EndUnboundLoad();
                    treeList1.ExpandAll();
                }

            }

        }
        #region TreeList 鼠标右键

        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (maxId > 0)
                {
                    toolStripComboBox1.Items.Clear();
                    for (int i = 0; i < maxId; i++)
                    {
                        toolStripComboBox1.Items.Add(i);
                    }
                    treeList1.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //全部展开
            treeList1.ExpandAll();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //全部折叠
            treeList1.CollapseAll();
        }

        private void toolStripComboBox1_TextChanged(object sender, EventArgs e)
        {
            string str = toolStripComboBox1.Text;
            if (str.Length > 0)
            {
                treeList1.CollapseAll();
                treeList1.ExpandToLevel(Convert.ToInt32(str));
                contextMenuStrip1.Close();
            }
        }
        #endregion
    }
}